/*
 * Copyright 2009-2010 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.model;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.MappedSuperclass;

import org.internna.iwebjtracker.project.model.Module;
import org.internna.iwebjtracker.project.model.Project;
import org.internna.iwebjtracker.project.model.Version;
import static org.internna.iwebmvc.utils.CollectionUtils.isEmpty;
import static org.internna.iwebmvc.utils.CollectionUtils.isNotEmpty;

/**
 * Handles all memberhsip (developers, administrators, ...) operations.
 *
 * @author Jose Noheda
 * @since 1.0
 */
@MappedSuperclass
public abstract class ProjectMembershipManager<M extends Module<P, M>, V extends Version<TrackerUser, P, V>, P extends Project<DefaultConnectionDetails, M, V, TrackerUser, P>> extends ProjectActivityManager<M, V, P> {

    private static final long serialVersionUID = 1345615091603146317L;

    @JoinTable(joinColumns = {
        @JoinColumn(name = "PROJECT", referencedColumnName = "ID", nullable = false)
    }, inverseJoinColumns = {
        @JoinColumn(name = "DEVELOPER", referencedColumnName = "ID", nullable = false)
    })
    @ManyToMany(fetch = FetchType.EAGER)
    private Set<TrackerUser> developers;

    @ManyToMany
    @JoinTable(joinColumns = {
        @JoinColumn(name = "PROJECT", referencedColumnName = "ID", nullable = false)
    }, inverseJoinColumns = {
        @JoinColumn(name = "OBSERVER", referencedColumnName = "ID", nullable = false)
    })
    private Set<TrackerUser> observers;

    /**
     * Accessor method. Ensures the collection is not modifiable.
     *
     * @return a not empty unmodifiable collection
     */
    public Set<TrackerUser> getDevelopers() {
        return isEmpty(developers) ? Collections.EMPTY_SET : Collections.unmodifiableSet(developers);
    }

    /**
     * Accessor method.
     */
    public void setDevelopers(Set<TrackerUser> developers) {
        this.developers = developers;
        if (developers != null) {
            for (TrackerUser dev : developers) {
                onAddMembership(dev);
            }
        }
    }

    /**
     * Accessor method
     *
     * @return a non null non modifiable collection
     */
    public Set<TrackerUser> getObservers() {
        return isEmpty(observers) ? Collections.EMPTY_SET : Collections.unmodifiableSet(observers);
    }

    /**
     * Establishes the new group of observers. If the provided collection is null
     * it clears the current one before.
     */
    public void setObservers(Set<TrackerUser> observers) {
        if ((observers == null) && (isNotEmpty(this.observers))) {
            this.observers.clear();
        }
        this.observers = observers;
    }

    /**
     * Records the interest of a user in this project.
     *
     * @param observer any
     */
    public final void addObserver(TrackerUser observer) {
        if ((observer != null) && (observer.getId() != null)) {
            if (observers == null) {
                observers = new HashSet<TrackerUser>();
            }
            observers.add(observer);
            onAddTracking(observer);
        }
    }

    /**
     * Adds a new member to this project. A developer is always an observer as well.
     *
     * @param developer any
     */
    public final void addDeveloper(TrackerUser developer) {
        if ((developer != null) && (developer.getId() != null)) {
            if (developers == null) {
                developers = new HashSet<TrackerUser>();
            }
            addObserver(developer);
            developers.add(developer);
            onAddMembership(developer);
        }
    }

    /**
     * Extension point for subclasses called when a new member wants to track this project.
     *
     * @param user a non null user.
     */
    protected abstract void onAddTracking(TrackerUser user);

    /**
     * Extension point for subclasses called when a new member is added successfully.
     *
     * @param user a non null user.
     */
    protected abstract void onAddMembership(TrackerUser user);

    /**
     * Delegates to getDevelopers()
     *
     * @return a not empty unmodifiable collection
     */
    @Override public final Collection<TrackerUser> getProjectMembers() {
        return getDevelopers();
    }

    /**
     * Filters the list of developers removing those users in the owners group and ensures the
     * result is not modifiable externally.
     *
     * @return a not empty unmodifiable collection
     */
    @Override public final Collection<TrackerUser> getProjectDevelopers() {
        Set<TrackerUser> devs = new HashSet<TrackerUser>();
        for (TrackerUser user : getProjectMembers()) {
            if (!isOwner(user.getSecurityUser())) {
                devs.add(user);
            }
        }
        return Collections.unmodifiableSet(devs);
    }

    /**
     * Filters the list of developers accepting those users in the owners group and ensures the
     * result is not modifiable externally.
     *
     * @return a not empty unmodifiable collection
     */
    @Override public final Collection<TrackerUser> getProjectAdministrators() {
        Set<TrackerUser> admins = new HashSet<TrackerUser>(getProjectMembers());
        admins.removeAll(getProjectDevelopers());
        return Collections.unmodifiableSet(admins);
    }

    /**
     * Checks members testing for the user in question.
     *
     * @param user any
     * @return any
     */
    @Override public final boolean isDeveloper(TrackerUser user) {
        return getProjectMembers().contains(user);
    }

    /**
     * Checks administrator members testing for the user in question.
     *
     * @param user any
     * @return any
     */
    @Override public final boolean isAdministrator(TrackerUser user) {
        return getProjectAdministrators().contains(user);
    }

    /**
     * Adds a member to this project. If the flag is true it includes the security user
     * in the owners group.
     *
     * @param user any
     * @param asAdministrator true if the user can update this entity from now on
     * @return true if the member list has a new element at the end
     */
    @Override public final boolean addMember(TrackerUser user, boolean asAdministrator) {
        boolean added = true;
        int members = getDevelopers().size();
        if (user instanceof TrackerUser) {
            TrackerUser trackerUser = (TrackerUser) user;
            addDeveloper(trackerUser);
            if (asAdministrator) {
                int owners  = getOwners() != null ? getOwners().size() : 0;
                addOwner(trackerUser.getSecurityUser());
                added = owners < (getOwners() != null ? getOwners().size() : 0);
            }
        }
        return added && (members < getDevelopers().size());
    }

}
